package com.dlgcy.ui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import com.dlgcy.weibo.ConfigUtil;
import com.dlgcy.weibo.DataProcessor;
import com.dlgcy.weibo.Forward;
import com.dlgcy.word.CopyDirectory;
import com.dlgcy.word.CreateFileUtil;
import com.dlgcy.word.DeleteFiles;
import com.dlgcy.word.MSWordManager;
import com.dlgcy.word.WordReader;
import com.dlgcy.word.WordToHtml;
import com.dlgcy.xinlang_weibo.Forward_xl;

public class MyFrame extends JFrame {

	JPanel leftPanel, rightPanel, panelInScroll;
	MyJScrollPane scrollPane;
	JButton paste, authorize, remove, doneWordPaste, forward, about, setting;
	JLabel nickLabel;

	String WORK_SPACE = ConfigUtil.getValue("WORK_SPACE");
	String WORK_WORD_PATH = WORK_SPACE + ConfigUtil.getValue("WORD_NAME");
	String WORK_HTML_PATH = WORK_SPACE + ConfigUtil.getValue("HTML_NAME");
	String WORK_PIC_PATH = WORK_SPACE + "html.files";
	MSWordManager wordManager = new MSWordManager(true);
	String contentStr;
	DataProcessor dataProcessor; // 数据处理对象；

	String[][] strArray;
	int strCount;
	int picCount;
	String[] picArray;

	public static String FILE_PATH = ConfigUtil.FILE_PATH; // 配置文件路径；

	public MyFrame() {
		super("转发精灵 新浪 V20130817 by 独立观察员");

		Container cont = this.getContentPane(); // 容器；
		cont.setLayout(new BorderLayout());
		leftPanel = new JPanel();
		rightPanel = new JPanel();
		scrollPane = new MyJScrollPane();
		cont.add(leftPanel, BorderLayout.WEST); // 添加面板到窗体；
		cont.add(rightPanel, BorderLayout.EAST);

		// scrollPane.getViewport().add(panelInScroll);
		leftPanel.add(scrollPane);

		rightPanel.setSize(100, 650);
		rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
		// 建立一个空的边界，并指定上下左右的宽度，在这些宽度中不能作绘图的效果;
		rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
		paste = new RightButton("粘贴内容");
		authorize = new RightButton("请授权");
		remove = new RightButton("移除授权");
		doneWordPaste = new RightButton("数据处理");
		forward = new RightButton("开始发送");
		about = new RightButton("关于");
		setting = new RightButton("设置");
		nickLabel = new JLabel("       ");

		// 先加入一个不可见的 Strut，从而使 topPanel 对顶部留出一定的空间
		rightPanel.add(Box.createVerticalStrut(8));
		rightPanel.add(nickLabel);
		rightPanel.add(Box.createVerticalStrut(8));
		rightPanel.add(authorize);
		// rightPanel.add(Box.createRigidArea(new Dimension(100,30))); //rigid
		// area 可设置长和宽；
		rightPanel.add(Box.createVerticalStrut(8));
		rightPanel.add(remove);
		rightPanel.add(Box.createVerticalStrut(40));
		rightPanel.add(paste);
		rightPanel.add(Box.createVerticalStrut(8));
		rightPanel.add(doneWordPaste);
		rightPanel.add(Box.createVerticalStrut(8));
		rightPanel.add(forward);
		rightPanel.add(Box.createVerticalStrut(40));
		rightPanel.add(setting);
		rightPanel.add(Box.createVerticalStrut(8));
		rightPanel.add(about);

		authorize.addActionListener(new ActionListener() { // 授权；
					@Override
					public void actionPerformed(ActionEvent e) {
						new AuthorizeFrame();

						/*
						 * Forward.init(); Forward.authorize();
						 */
						about_Authorize();
					}
				});

		remove.addActionListener(new ActionListener() { // 移除授权；
			@Override
			public void actionPerformed(ActionEvent e) {
				String value = ConfigUtil.getValue("ACCESS_TOKEN");
				ConfigUtil.deleteKeyValue4Pro("ACCESS_TOKEN", value, ConfigUtil.FILE_PATH);
				about_Authorize();
				JOptionPane.showMessageDialog(remove, new JLabel("已成功移除授权！请重启软件。"), "移除授权", JOptionPane.INFORMATION_MESSAGE);
			}
		});

		paste.addActionListener(new ActionListener() { // 粘贴数据；
			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					DeleteFiles.deleteFile(WORK_WORD_PATH); // 清理工作空间；
					DeleteFiles.deleteFile(WORK_HTML_PATH);
					DeleteFiles.deleteDirectory(WORK_PIC_PATH);
				} catch (Exception e1) {
					e1.printStackTrace();
				}

				try {
					doneWordPaste.setEnabled(true);
					doneWordPaste.setText("下一步");
					forward.setText("开始发送");

					wordManager = new MSWordManager(true);
					try {
						Desktop.getDesktop().open(new File(WORK_WORD_PATH)); // 打开工作word；

					} catch (IllegalArgumentException e) {
						e.printStackTrace();
						wordManager.createNewDocument(WORK_WORD_PATH);
						wordManager.paste();
						// Desktop.getDesktop().open(new File(WORK_WORD_PATH));
					}
					// scrollPane.getViewport().add(test());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		doneWordPaste.addActionListener(new ActionListener() { // 完成粘贴，数据处理；
					@Override
					public void actionPerformed(ActionEvent e) {
						doneWordPaste.setEnabled(false);
						doneWordPaste.setText("提交处理中");

						contentStr = WordReader.getTextFromWord(WORK_WORD_PATH);
						WordToHtml.wordToHtml(WORK_WORD_PATH, WORK_HTML_PATH);
						dataProcessor = new DataProcessor(contentStr); // 数据处理对象；
						strArray = dataProcessor.strArray;
						strCount = dataProcessor.strCount;
						picCount = dataProcessor.picCount;
						picArray = dataProcessor.picArray;

						JPanel p = new JPanel();
						p.add(new JTextArea(contentStr));
						scrollPane.getViewport().add(p);

						doneWordPaste.setText("处理完成");
						forward.setEnabled(true);
					}
				});

		forward.addActionListener(new ActionListener() { // 发送；
			@Override
			public void actionPerformed(ActionEvent e) {
				forward.setEnabled(false);
				// forward.setText("正在发送");

				Forward.init(); // 需要的参数赋值；

				if (strCount != picCount) { // 图文数目不对；
					Object[] options = { "发送", "取消" };
					int response = JOptionPane.showOptionDialog(forward, new JLabel("文字段数与图片张数不一致，强制发送可能会出错。确定要强制发送吗？"), "是否要发送？", JOptionPane.WARNING_MESSAGE,
							JOptionPane.YES_NO_OPTION, null, options, options[1]);
					if (response == 0) {// 用户要发送；
						JOptionPane.showMessageDialog(forward, new JLabel("开始发送"));
						new Thread(new Runnable() {
							@Override
							public void run() {
								startToSend();
							}
						}).start();
					} else {
						JOptionPane.showMessageDialog(forward, new JLabel("已取消发送"));
						try {
							restart();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
				} else {// 图文数目对应；
					JOptionPane.showMessageDialog(forward, new JLabel("开始发送"));
					new Thread(new Runnable() {
						@Override
						public void run() {
							startToSend();
						}
					}).start();
				}
			}
		});

		setting.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new SettingFrame();
			}
		});

		about.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JFrame f = new JFrame();
				JPanel aboutPanel = new JPanel();
				aboutPanel.add(new JLabel(new ImageIcon("image/logo.png")));
				aboutPanel.add(new LinkLabel("我的空间", "http://user.qzone.qq.com/1101787191/main"));

				f.add(aboutPanel);
				f.pack();
				f.setLocation(300, 10);
				f.setVisible(true);
			}
		});
	}

	public void startToSend() {
		int i, n;
		JPanel show = new JPanel();
		show.setLayout(new BoxLayout(show, BoxLayout.Y_AXIS));
		String access_token = ConfigUtil.getValue("ACCESS_TOKEN");
		String content;

		if (access_token.equals("")) {// 未授权；
			JOptionPane.showMessageDialog(forward, new JLabel("请先授权！"), null, JOptionPane.WARNING_MESSAGE);
			forward.setText("未发送");
		} else { // 已授权；
			for (i = 0; i < strCount; i++) {
				content = strArray[i][0] + strArray[i][1] + "\r\n";
				// Forward.sendTextAndPic(content, picArray[i]); // 已有延时；
				Forward_xl.upload(access_token, content, picArray[i]);
				n = i + 1;
				forward.setText("正在发送" + n);
				show.add(new ShowItem(strArray[i][0], strArray[i][1], picArray[i]));
				scrollPane.getViewport().add(show);
			}
			if (i == strCount) {
				JOptionPane.showMessageDialog(forward, new JLabel("已全部发送完成！"));
			} else {
				JOptionPane.showMessageDialog(forward, new JLabel("发送结束，发送不完全！"));
			}
			forward.setText("发送结束");
		}
	}

	// 获取图文；
	public JPanel test() throws Exception {
		final JPanel panel = new JPanel();

		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
					Transferable clipT = clipboard.getContents(null);
					// if(!clipT.isDataFlavorSupported(DataFlavor.imageFlavor)
					// || !clipT.isDataFlavorSupported(DataFlavor.stringFlavor)
					// )
					// throw new
					// RuntimeException("Get some string and image in your clipboard, please!!");
					if (clipT.isDataFlavorSupported(DataFlavor.imageFlavor)) {
						Image image = (Image) clipT.getTransferData(DataFlavor.imageFlavor);
						BufferedImage bfImg = Alpha.toBufferedImage(image);
						byte[] b = Alpha.transferAlpha(image); // 去除背景色；
						bfImg = Alpha.ByteToBufferedImage(b);
						panel.add(new JLabel(new ImageIcon(bfImg)), BorderLayout.CENTER);

						// savePic(bfImg); //保存图片；
					} else if (clipT.isDataFlavorSupported(DataFlavor.stringFlavor)) {
						String text = (String) clipT.getTransferData(DataFlavor.stringFlavor);
						panel.add(new JTextArea(text), BorderLayout.SOUTH);
					} else {
						// throw new
						// RuntimeException("Get some string and image in your clipboard, please!!");
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		return panel;
	}

	public BufferedImage strip(BufferedImage image) throws IOException {// 跳过开头8字节（好像无效）；
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ImageIO.write(image, "jpg", out);

		byte[] origionalByteImage = out.toByteArray();
		int len = origionalByteImage.length;
		byte[] finalByteImage = new byte[len - 8];
		for (int i = 8; i < len; i++) {
			finalByteImage[i - 8] = origionalByteImage[i];
		}
		BufferedImage finalImage = Alpha.ByteToBufferedImage(finalByteImage);

		return finalImage;
	}

	protected static String getClipboardText() throws Exception {
		Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();// 获取系统剪贴板
		// 获取剪切板中的内容
		Transferable clipT = clip.getContents(null);
		if (clipT != null) {
			// 检查内容是否是文本类型
			if (clipT.isDataFlavorSupported(DataFlavor.stringFlavor))
				return (String) clipT.getTransferData(DataFlavor.stringFlavor);
		}
		return null;
	}

	// 从剪切板读取图像
	public static Image getImageFromClipboard() throws Exception {
		Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable cc = sysc.getContents(null);
		if (cc == null)
			return null;
		else if (cc.isDataFlavorSupported(DataFlavor.imageFlavor))
			return (Image) cc.getTransferData(DataFlavor.imageFlavor);
		return null;
	}

	public void savePic(BufferedImage image) {
		int w = image.getWidth(this);
		int h = image.getHeight(this);

		// 首先创建一个BufferedImage变量，因为ImageIO写图片用到了BufferedImage变量。
		BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);

		// 再创建一个Graphics变量，用来画出来要保持的图片，及上面传递过来的Image变量
		Graphics g = bi.getGraphics();
		try {
			g.drawImage(image, 0, 0, null);

			// 将BufferedImage变量写入文件中。
			ImageIO.write(bi, "jpg", new File("d:/gray11.jpg"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void about_Authorize() {
		// ConfigUtil.start();
		if (ConfigUtil.getValue("ACCESS_TOKEN").equals("")) { // 若要重新授权，将配置文件中该项删除；
			authorize.setEnabled(true);
			authorize.setText("请授权");
			remove.setEnabled(false);
		} else {
			authorize.setEnabled(false);
			authorize.setText("已授权");
			remove.setEnabled(true);

		}
	}

	public static void restart() throws IOException {// 用一条指定的命令去构造一个进程生成器 
		/*
		 * ProcessBuilder pb = new ProcessBuilder("java","-jar","MyFrame.jar");
		 * //让这个进程的工作区空间改为F:\dist ,这样的话,它就会去F:\dist目录下找Test.jar这个文件         
		 * //pb.directory(new File("F:\\dist")); //得到进程生成器的环境 变量,这个变量我们可以改,
		 * 改了以后也会反应到新起的进程里面去 Map<String,String> map = pb.environment(); Process
		 * p = pb.start();//然后就可以对p做自己想做的事情了 //自己这个时候就可以退出了         
		 * System.exit(0);
		 */

		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				try {
					Runtime.getRuntime().exec("java MyFrame");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		System.exit(0);
	}

	// 设置窗口显示效果；
	public void showMe() {
		this.setSize(740, 700);
		// this.pack(); //自动设置大小；
		setResizable(false); // 不允许改变大小；
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocation(300, 10);
		setVisible(true);
		setIconImage(new ImageIcon("image/threeKnives.png").getImage());

		doneWordPaste.setEnabled(false);
		forward.setEnabled(false);

		new Thread(new Runnable() {// 显示用户名；
					@Override
					public void run() {
						if (!(ConfigUtil.getValue("ACCESS_TOKEN").equals(""))) {
							nickLabel.setText(ConfigUtil.getValue("USER_NAME"));
						}
					}
				}).start();
	}

	public static void main(String[] args) {
		String currentDir = System.getProperty("user.dir");
		System.out.println(currentDir);
		String WORK_SPACE = ConfigUtil.getValue("WORK_SPACE");
		MyFrame myFrame = new MyFrame();

		if (ConfigUtil.getValue("FIRST_OPEN").equals("yes")) {// 复制dll文件；

			try {
				CopyDirectory.copyDirectiory("dll", "C://Windows//System32");
			} catch (IOException e) {
				e.printStackTrace();
				String jre_Path = System.getProperty("java.home") + "//bin";
				try {
					CopyDirectory.copyDirectiory("dll", jre_Path);
				} catch (IOException e1) {
					ConfigUtil.setValueAndSave("FIRST_OPEN", "no", FILE_PATH);
					JOptionPane.showMessageDialog(myFrame.leftPanel, new JLabel("请将软件目录的dll目录下的文件拷贝到。。。（该目录下有介绍）"), "请拷贝dll", JOptionPane.WARNING_MESSAGE);
					e1.printStackTrace();
				}
			}
		}

		myFrame.showMe();
		myFrame.about_Authorize();
		CreateFileUtil.createDir(WORK_SPACE);
	}
}
